/*   Valhalla MailChecker -- Simple IMAP Mail Checker
*    Copyright (C) 2010-2011  Guillaume Florimond (gflorimond at gmail dot com)
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package fr.valhalla.mailcheck.gui;

import fr.valhalla.mailcheck.Checker;
import fr.valhalla.mailcheck.GlobalPreferences;
import fr.valhalla.mailcheck.Kernel;
import fr.valhalla.mailcheck.utils.SystemUtils;
import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.util.Iterator;
import java.util.Vector;

/**
 *
 * @author gf
 */
public class SysTray {
    // Préférences
    GlobalPreferences prefs;

    // Desktop
    Desktop desktop;

    // System Tray
    final PopupMenu popup = new PopupMenu();
    final SystemTray tray = SystemTray.getSystemTray();
    
    // Création de l'icone
    final URL imageURL = getClass().getResource("/fr/valhalla/mailcheck/resources/images/Email.png");
    final Image image = Toolkit.getDefaultToolkit().createImage(imageURL);
    final TrayIcon trayIcon = new TrayIcon(image, "Valhalla MailCheck");

    // Boutons du menu
    protected MenuItem aboutItem;
    protected MenuItem exitItem;
    protected MenuItem displayFrameItem;
    protected MenuItem desktopClientItem;
    protected MenuItem globalPreferencesItem;
    protected CheckboxMenuItem displayTooltipCheckItem;

    public SysTray(Kernel kernel) {
        prefs = kernel.getGlobalPreferences();
        final Kernel k = kernel;

        // Taille de l'icone
        trayIcon.setImageAutoSize(true);

        // Création du popup
        aboutItem = new MenuItem("À Propos...");
        globalPreferencesItem = new MenuItem("Préférences...");
        displayFrameItem = new MenuItem("Afficher la fenêtre");
        displayTooltipCheckItem = new CheckboxMenuItem("Afficher le tooltip");
        desktopClientItem = new MenuItem("Nouveau message...");
        exitItem = new MenuItem("Quitter");
        Menu checkersMenu = new Menu("Comptes");

        // Ajout des composants du popup
        popup.add(aboutItem);
        popup.add(globalPreferencesItem);
        popup.addSeparator();
        popup.add(displayFrameItem);
        popup.add(displayTooltipCheckItem);
        popup.add(desktopClientItem);
        popup.addSeparator();
        popup.add(checkersMenu);
        popup.add(exitItem);

        // Desktop actions (lancement du client e-mail par défaut)
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.MAIL)) {
                desktopClientItem.setEnabled(true);
                desktopClientItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        try {
                            desktop.mail();
                        } catch(Exception e) {e.printStackTrace();}
                    }
                });
            } else {
                desktopClientItem.setEnabled(false);
            }
        } else {
            desktopClientItem.setEnabled(false);
        }

        // Ajout des gestionnaires d'événement
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // le comportement varie selon l'OS utilisé
                if(SystemUtils.IS_OS_MAC_OSX) {
                    // Clic-gauche : ne rien faire, OS X affiche le menu
                    // Clic-droit : afficher/cacher la fenêtre
                    if(e.getButton() == e.BUTTON3 || e.getButton() == e.BUTTON2)
                        k.getAccountList().toggleShow();
                }
                else if(SystemUtils.IS_OS_WINDOWS) {
                    // Clic-gauche : afficher/cacher la fenêtre
                    // Clic-droit : ne rien faire, Windows affiche le menu
                    if (e.getButton() == e.BUTTON1) {
                        k.getAccountList().toggleShow();
                    }
                } else if (SystemUtils.IS_OS_LINUX) {
                    // Clic-gauche : afficher/cacher la fenêtre
                    // Clic-droit : ne rien faire, KDE/Gnome affichent le menu
                    if (e.getButton() == e.BUTTON1) {
                        k.getAccountList().toggleShow();
                    }
                } else {
                    // Clic-gauche : afficher/cacher la fenêtre
                    // Clic-droit : ne rien faire
                    if (e.getButton() == e.BUTTON1) {
                        k.getAccountList().toggleShow();
                    }
                }
            }
        });

        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                About ab = new About();
            }
        });

        globalPreferencesItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                GlobalPreferencesFrame gpf = new GlobalPreferencesFrame();
            }
        });

        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                System.exit(0);
            }
        });

        displayFrameItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                k.getAccountList().setVisible(true);
            }
        });

        displayTooltipCheckItem.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent evt) {
                
            }
        });

        // Ajout des entrées du menu qui correspondent aux checkers/comptes
        @SuppressWarnings("UseOfObsoleteCollectionType")
        Vector cks = kernel.getCheckers();
        Iterator i = cks.iterator();
        while(i.hasNext()) {
            final Checker next = (Checker)i.next();
            MenuItem mi = new MenuItem(next.getAccount().getAccountName());
            checkersMenu.add(mi);
            mi.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    next.showCheckFrame();
                }
            });
        }
        

        // Insertion du popup dans le system tray
        trayIcon.setPopupMenu(popup);

        // Ajout de l'icone au system tray
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }
    }


}
